<template>
  <div class="sale">
    <div class="top_button">
      <div class="partition"></div>
    </div>
<!-- <div id="eagleMapContainer" :class="open_status?'':'table_box'" @scroll="hanldeScroll"> -->
  <!-- <div v-if="eventType===0" id="table_list"> -->
  <div id="eagleMapContainer"  @scroll="hanldeScroll">
  <div id="table_list">

      <!-- height="calc(100vh - 90px)" -->
    <el-table
      :data="list"
      border
      v-loading="isres"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      style="width: 100%"
      :show-summary=true
      :summary-method="getSummaries"
    >
      <el-table-column type="index" width="50" label="序号"></el-table-column>
      <el-table-column
        v-for="(col, i) in cols"
        :key="i"
        :prop="col"
        :label="col"
        sortable
      ></el-table-column>
      <el-table-column align="right"  width="140" type="expand">
        <template #header>
          修改
        </template>
        <template #default="props">
          <el-table
            style="width: 100%"
            border
            :data="
              alldata.filter((data) => {
                if (!data['商品编码']) {
                  return;
                }
                return (
                  !props.row['商品编码'] ||
                  data['商品编码'].includes(props.row['商品编码'])
                );
              })
            "
          >
            <el-table-column
              type="index"
              width="50"
              label="序号"
            ></el-table-column>
            <el-table-column
              v-for="(col, i) in slotcols"
              :key="i"
              :prop="col"
              :label="col"
              sortable
            ></el-table-column>
            <el-table-column fixed="right" width="200">
              <template #default="scope">
                <div class="update" style="display:flex;">
                <div>
                  <el-input
                    v-model="scope.row.inputdqr"
                    tr="current-row-key"
                    placeholder="修改到期日"
                    class="num"
                  ></el-input>
                  <el-input
                    v-model="scope.row.inputnum"
                    tr="current-row-key"
                    placeholder="修改数量"
                    class="num"
                  ></el-input>
                </div>

                <el-button
                  class="baocun"
                  @click="
                    preservation(
                      scope.row.id,
                      scope.row['数量'],
                      scope.row['到期日'],
                      scope.row.inputnum,
                      scope.row.inputdqr
                    )
                  "
                  type="primary"
                  plain
                  >保存</el-button
                >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
    </el-table>
        
  </div>
</div>
  </div>
  <tool :multipleTable="sale"></tool>
</template>
<script>
import { reactive, toRefs,nextTick } from "vue";
import { imptable,Inventory, updqr } from "@/api/pandian";
import { ElMessage } from "element-plus";
import tool from "./components/tool";
export default {
  components: {
    tool,
  },
  setup() {
    const data = reactive({
      cols: [],
      sale: [],
      isres: false,
      search: "",
      alldata:[],
      slotcols:[],
      listPage:0,
      loading:false,
      list:[],
      scrollTop:0,
    });
    const loaded = async () => {
      data.isres = true;

      const result = await imptable.get();
      data.isres = false;
      if (result.data.length == 0) {
        data.sale = [];
        ElMessage.success({
          message: "还没有盘呢",
          type: "success",
        });
      } else {
        data.sale = result.data;
        data.list=data.sale.slice(0, 30)
        data.cols = Object.keys(result.data[0]);
      }
      const res = await Inventory.get();
      data.alldata = res.data.map((o) => {
          return {
             id:o.id, 
             盘点人:o.user1, 
             仓库:o.ck,
             商品编码:o.pc,
             商品名称:o.pn,
             到期日:o.dqr_dd,
             数量:o.pd, 
          };
        });
      data.slotcols = Object.keys(data.alldata[0]);
    };
    const getSummaries = (param) => {
      const { columns,data } = param;
      const sums = [];
      columns.forEach((column, index) => {
          if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (index === 4) {
        const values = data.map(item => Number(item[column.property]));
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            }
      });
      return sums;
    };
    const preservation = async (id, num, dqr, newnum, newdqr) => {
      const result = await updqr.post({
        id,
        upnum: newnum ? newnum : num,
        updqr: newdqr ? newdqr : dqr,
      });
      if (result.code == 200) {
        ElMessage.success({
          message: "恭喜你，这是一条成功消息",
          type: "success",
        });
        data.alldata.filter(
          (data) =>{
            if(data['id']==id){
              data['数量']= newnum ? newnum : num;
              data['到期日']= newdqr ? newdqr : dqr;
            }   
          } 
        )
      } else {
        ElMessage.success({
          showClose: true,
          message: "错了哦，这是一条错误消息",
          type: "error",
        });
      }
    };
    const dynamicTable=()=>{
      const clientHeight=document.body.clientHeight;
      console.log(clientHeight/63);
      // let items=clientHeight/30;
      // data.sale=items
    }
    dynamicTable();
//     const onScroll=(evt) =>{
//   // 判断是否是我们需要响应的滚动事件
//   if (evt.target === this.scrollingContainer.current) {
//     const { scrollTop } = evt.target;
//     const { startIndex, total, rowHeight, limit } = this;

//     // 计算当前startIndex
//     const currentStartIndex = Math.floor(scrollTop / rowHeight);

//     // 如果currentStartIndex 和 startIndex 不同（我们需要更新数据了）
//     if (currentStartIndex !== startIndex ) {
//       this.startIndex = currentStartIndex;
//       this.endIndex = Math.min(currentStartIndedx + limit, total - 1);
//       this.setState({ scrollTop });
//     }
//   }
// }
const hanldeScroll=(e)=> {
      // 获取eagleMapContainer的真实高度
      const boxHeight = document.getElementById('eagleMapContainer').offsetHeight
      // 获取table_list的真实高度（浮动内容的真实高度）
      const tableHeight = document.getElementById('table_list').offsetHeight
      // boxHeight和滑块浮动的高度相差小于50 && 不在加载中 && 不是最后一页 
      if (tableHeight - (e.target.scrollTop + boxHeight) < 50 && !data.loading && data.listPage < (data.sale.length / 30)) {
        // 第一次触发时，记录滑块高度
        // data里scrollTop，listPage默认为0
        if (!data.scrollTop) {
          data.scrollTop = e.target.scrollTop
        }
        // 触发下拉加载更多
        queryMoreStat(true, tableHeight, boxHeight)
      } else if (e.target.scrollTop === 0 && !data.loading) {
        // 如果滑块上拉到顶部，则向上加载300条
        queryMoreStat(false, tableHeight, boxHeight)
      }
    };
    const queryMoreStat=async (type, tableHeight, boxHeight)=> {
      data.loading = true
      // 触底加载
      if (type) {
      console.log("触底加载")
        data.listPage = data.listPage + 1
        const centerPage = data.listPage * 30
        const startPage = centerPage >= 30 ? centerPage - 30 : centerPage
        const endPage = centerPage + 60
        const newList = data.sale.slice(startPage, endPage)
        if (data.listPage > 0) {
          const box = document.getElementById('eagleMapContainer')
          // 视图跳到触发的数据，补回50的高度差值
          box.scrollTop = data.scrollTop + 50
        }
        data.list = newList
      } else {
        console.log("置顶加载")
        // 置顶加载
        if (data.listPage > 0) {
          data.listPage = data.listPage - 1
          const centerPage = data.listPage * 30
          const startPage = centerPage >= 30 ? centerPage - 30 : centerPage
          const endPage = centerPage + 60
          const newList = data.sale.slice(startPage, endPage)
          if (data.listPage > 0) {
            const box = document.getElementById('eagleMapContainer')
            box.scrollTop = tableHeight - data.scrollTop - boxHeight
          }
          data.list = newList
        } else {
          data.list = data.sale.slice(0, 30)
        }
      }
      await nextTick();
        data.loading = false
    }
    loaded();
    return { ...toRefs(data), getSummaries,preservation,hanldeScroll };
  },
};
</script>
<style scoped>
#eagleMapContainer{
   overflow-y: auto;
   margin-top: 10px;
   min-height: 150px;
   max-height: calc(100vh - 120px);
 }
 #eagleMapContainer::-webkit-scrollbar {
    width: 6px; /*对垂直流动条有效*/
    height: 6px;
  }
  #eagleMapContainer::-webkit-scrollbar-track{
    background-color:rgba(0,0,0,0.1);
  }
  #eagleMapContainer::-webkit-scrollbar-thumb{
    border-radius: 6px;
    background-color: rgba(0,0,0,0.2);
  }
  /*定义右下角汇合处的样式*/
  #eagleMapContainer::-webkit-scrollbar-corner {
    background:rgba(0,0,0,0.2);
  }
</style>
